// pages/goods/index.js
import {request,fail,ok} from "../../util"
import Dialog from '@vant/weapp/dialog/dialog';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    sliderCurrent: 0,
    goodsId:undefined,
    goods:undefined,
    minPrice:undefined,
    maxPrice:undefined,
    paramsShow:false,
    goodsParamsKeys:[],
    richTextContent:undefined,
    skusShow:false,
    skuChoosed:undefined,
    collected:false,
    cartCount:0,
    cartList:[],
    //0代表购物车 1代表直接购买
    chooseType:0,
    chooseValue:1,
    //控制购物车弹框
    cartShow:false,
    //购物车是否全选
    cartAllChoose:false,
    //购物车选择的项，存的cartId，但是string型
    cartChoose:[],
    //统计价格
    cartChoosePrice:0.0
  },
  refreshPriceAndCheckBox(){
    let cartChoose= this.data.cartChoose
    let cartList= this.data.cartList
    this.setData({cartAllChoose:cartChoose.length===cartList.length  })
    let cartChoosePrice=0.0
    cartChoose.forEach(e=>{
      let cart=  cartList.find( c=> c.cartId=== parseInt(e) )
      cartChoosePrice+= (cart.price* cart.amount)
    })
    this.setData({cartChoosePrice})
  },
  onChangeAllChoose(e){
    this.setData({
      cartAllChoose: e.detail,
    });
    let cartList= this.data.cartList
    let cartChoose=[]
    if(this.data.cartAllChoose){
      for(let i=0;i<cartList.length;i++){
        cartChoose.push(cartList[i].cartId.toString())
      }
    }
    
    this.setData({cartChoose})
    this.refreshPriceAndCheckBox()
  },
  cartChooseChange(e){
    this.setData({
      cartChoose: e.detail,
    });
    this.refreshPriceAndCheckBox()
  },
  changeChooseValue(e){
    let num= parseInt(e.currentTarget.dataset.id)
    if(this.data.chooseValue+num<=0){
      this.setData({chooseValue:1})
    }else{
      this.setData({chooseValue:this.data.chooseValue+num})
    }
  },
  inputChooseValue(e){
    let amount= !e.detail.value? 1: parseInt(e.detail.value)
    amount= amount<=0?1:amount;
    this.setData({chooseValue:amount})
  },
  setCartAmountByOne(e){
    let amount= parseInt(e.currentTarget.dataset.num)+ 
    parseInt((e.currentTarget.dataset.a))
    amount= amount<=0?1:amount;
    let cartId= parseInt(e.currentTarget.dataset.id)
    this.reqSetCartAmount(amount,cartId)
  },
  reqSetCartAmount(amount,cartId){
    request({
      url:"/cart/sku/set",
      method:"POST",
      data:{
        amount,
        cartId
      }
    }).then(res=>{
      this.getCartCount()
      let cartList= this.data.cartList
      for(let i=0;i<cartList.length;i++){
        if(cartList[i].cartId===cartId){
          cartList[i]["amount"]= amount
          break
        }
      }
      this.setData({cartList})
      this.refreshPriceAndCheckBox()
    })
  },
  setCartAmount(e){
    let amount= !e.detail.value? parseInt((e.currentTarget.dataset.a)):
     parseInt(e.detail.value)
    amount= amount<=0?1:amount;
    let cartId= parseInt(e.currentTarget.dataset.id)
    this.reqSetCartAmount(amount,cartId)
  },
  deleteCart(e){
    let cartId= parseInt(e.currentTarget.dataset.id)

    Dialog.confirm({
      title: '从购物车删除',
      message: '确认删除?',
    })
      .then(() => {
        request({
          url:"/cart/delete?cartId="+cartId,
          method:"POST"
        }).then(res=>{
          this.getCartList()
          this.getCartCount()
          //删除购物车选择项
          let cartChoose=this.data.cartChoose
          for(let i=0;i<cartChoose.length;i++){
            if(parseInt(cartChoose[i])=== cartId){
              cartChoose.splice(i,1)
              break
            }
          }
          this.setData({cartChoose})
        })
      })
      .catch(() => {
        // on cancel
      });

    
  },
  toPrepay(){
    if(!this.data.cartChoose||this.data.cartChoose.length===0){
      fail("请选择商品")
      return
    }
  
    wx.navigateTo({
      url: '/pages/prepay/index?cartIds='+ this.data.cartChoose.join(","),
    })
  },
  clickAddCartOrBuy(){
    if(!this.data.skuChoosed){
      fail("请选择规格")
      return
    }

    if(this.data.chooseType===0){
      request({
        url:"/cart/sku/add",
        method:"POST",
        data:{
          "skuId":  this.data.skuChoosed.skuId,
          "amount": this.data.chooseValue,
          "type": false
        }
      }).then(res=>{
         this.getCartCount()
         this.setData({skusShow:false})
         ok("加入成功")
         this.refreshPriceAndCheckBox()
      })
    }else if(this.data.chooseType===1){
      request({
        url:"/cart/sku/add",
        method:"POST",
        data:{
          "skuId":  this.data.skuChoosed.skuId,
          "amount": this.data.chooseValue,
          "type": true
        }
      }).then(res=>{
          wx.navigateTo({
            url: '/pages/prepay/index?cartIds='+res.data,
          })
      })
    }
    
  },
  clickSku(e){
    let sku=e.currentTarget.dataset.id
    if(this.data.skuChoosed && this.data.skuChoosed.skuId=== sku.skuId  ){
      this.setData({skuChoosed:null})
    }else{
      this.setData({skuChoosed:sku})
    }
  },
  onParamsShow(){
    this.setData({paramsShow:!this.data.paramsShow})
  },
  onCartShow(){
    this.setData({cartShow:!this.data.cartShow})
    if(this.data.cartShow){
      this.getCartList()
    }
  },
  cartloadMore(){
    // console.log("触底分页");
  },
  onSkusShow(e){
    if(e.currentTarget.dataset.id){
      this.setData({chooseType:parseInt(e.currentTarget.dataset.id)})
    }
    this.setData({skusShow:!this.data.skusShow})
  },
  sliderChange(e){
    //console.log(e);
    this.setData({sliderCurrent:e.detail.current})
  },
  /**
   * 生命周期函数--监听页面加载
   */
  getCollect(){
    request({
      url:"/user/collect?goodsId="+this.data.goodsId
    }).then(res=>{
      this.setData({collected:res.data})
    })
  },
  getCartCount(){
    request({
      url:"/cart/count"
    }).then(res=>{
      this.setData({cartCount:res.data})
    })
  },
  getCartList(){
    request({
      url:"/cart/list?pageShow=false"
    }).then(res=>{
      this.setData({cartList:res.data.list})
      this.refreshPriceAndCheckBox()
    })
  },
  onClickCollect(){
    request({
      url:"/user/collect?goodsId="+this.data.goodsId,
      method:"POST"
    }).then(res=>{
      this.setData({collected:res.data})
    })
  },
  onLoad(options) {
    this.setData({goodsId:parseInt(options.id)})
    //搜藏状态
    this.getCollect()
    //购物车数量
    this.getCartCount()
    request({
      url:"/goods/detail?goodsId="+ this.data.goodsId
    }).then(res=>{
        this.setData({goods:res.data})
        if(res.data.params){
          this.setData({goodsParamsKeys:Object.keys(res.data.params)})
        }
        if(res.data.detailIntro){
          this.setData({richTextContent:res.data.detailIntro.replace(/\<img/gi, '<img style="width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"')})}

        if(res.data.skus && res.data.skus.length>0){
          let minPrice= res.data.skus[0].price
          let maxPrice= minPrice

          res.data.skus.forEach(e => {
              if(e.price> maxPrice){maxPrice= e.price} 
              if(e.price< minPrice){minPrice=e.price}
          });

          this.setData({minPrice})
          this.setData({maxPrice})
        }
        
    })
    //console.log(options);

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})